<template>
  <div class="case">
    <na-table
      :datas.sync="tableData"
      :searchObj.sync="search"
      @updateDatas="getDataLists"
      @newAdd="newAddClick"
    >
    </na-table>
    <!-- 新建报废单   -->
    <el-dialog
      :title="ops === 'modify' ? '修改物料报废' : '新建物料报废'"
      :visible.sync="isAddDialog"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <div class="subTip">
          <span class="mr15"
            ><span class="mr5">报废单号：</span
            >{{ scrapForm.scrapBillNo || "系统自动生成" }}</span
          >
          <span class="mr15"
            ><span class="mr5">创建日期：</span
            >{{ scrapForm.createTime || dayjs().format("YYYY-MM-DD") }}</span
          >
          <span
            ><span class="mr5">创建人员：</span
            >{{ ops === "add" ? name : scrapForm.createPersonName }}</span
          >
        </div>
        <div class="addWuliaoBox">
          <el-form
            ref="scrapForm"
            :model="scrapForm"
            :rules="rules"
            label-width="110px"
            label-position="left"
            class="dialogForm dialogInlineForm"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="报废类型">
                  <el-select
                        filterable
                    v-model="scrapForm.scrapBillType"
                    placeholder="请选择报废类型"
                    size="mini"
                  >
                    <el-option
                      v-for="item in scrapBillTypeList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="报废人员">
                  <el-input
                    v-model="scrapForm.scrapPersonName"
                    placeholder="请输入内容"
                    size="mini"
                  >
                    <template slot="append">
                      <el-button
                        slot="append"
                        icon="el-icon-user"
                        @click="isperShow = true"
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item
              label="报废备注"
              class="inlineText"
              prop="scrapRemark"
            >
              <el-input
                v-model="scrapForm.scrapRemark"
                type="textarea"
                :rows="1"
                placeholder="请输入报废备注"
                size="mini"
                clearable
              />
            </el-form-item>
          </el-form>
          <div class="tableBox flex flex_column">
            <div class="tt flex flex_between">
              <span class="fw">报废明细</span>
            </div>
            <div ref="bigdialogTable" class="bigdialogTbCon">
              <el-table :data="scrapForm.detailList" :row-key="(row) => row.rowKey" border style="width: 100%">
                <el-table-column
                prop="goodsCode"
                width="150"
                align="center"
                label="规格编号"
              >
                <template slot-scope="scope">
                  {{ scope.row.specificationCode || "--" }}
                </template>
              </el-table-column>
                <el-table-column
                  label="物料类型"
                  prop="categoryName"
                  min-width="90"
                />
                <el-table-column
                  prop="school"
                  width="150"
                  align="center"
                  label="供应商"
                >
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.supplierCode"
                      placeholder="请选择供应商"
                      filterable
                      size="small"
                      @change="supplierChange(scope.row, $event)"
                    >
                      <el-option
                        :key="item.supplierID"
                        :label="item.supplierName"
                        :value="item.supplierCode"
                        v-for="(item, index) in allSupliers"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="school"
                  width="150"
                  align="center"
                  label="物料名称"
                >
                  <template slot-scope="scope">
                    <el-select
                        filterable
                      v-model="scope.row.goodsCode"
                      placeholder="请选择物料"
                      size="small"
                      @change="
                        handleMaterialNameChange(
                          scope.row,
                          scope.$index,
                          $event
                        )
                      "
                    >
                      <el-option
                        :label="item.goodsName"
                        :value="item.goodsCode"
                        v-for="(item, index) in scope.row.materialList"
                        :key="index"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="specificationCode"
                  width="150"
                  align="center"
                  label="规格型号"
                >
                  <template slot-scope="scope">
                    <el-select
                        filterable
                      v-model="scope.row.specificationCode"
                      @change="handleSpecificationChange(scope.row, scope.$index,$event)"
                      placeholder="请选择规格型号"
                      size="small"
                    >
                      <el-option
                        :label="item.specificationName"
                        :value="item.specificationCode"
                        v-for="(item, index) in scope.row
                          .goodsSpecificationList"
                        :key="index"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                prop="productionBatchCode"
                width="150"
                align="center"
                label="生产批次"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.productionBatchNumber"
                    @change="handleBatchChange(scope.row, $event)"
                    filterable
                    value-key="productionBatchCode"
                    placeholder="请选择生产批次"
                    size="small"
                  >
                    <el-option
                      :label="item.productionBatchNumber"
                      :value="item"
                      v-for="(item, index) in scope.row.productionBatchList"
                      :key="index"
                    />
                  </el-select>
                </template>
              </el-table-column>
                <el-table-column
                  label="库存数量"
                  prop="stockQuantity"
                  show-overflow-tooltip
                  min-width="120"
                />
                <el-table-column
                  label="出库库位"
                  show-overflow-tooltip
                  prop="stockArea"
                  min-width="150"
                >
                  <template slot-scope="{ row }">
                    <el-cascader
                      v-model="row.stockArea"
                      :show-all-levels="false"
                      size="mini"
                      :options="storageLocations"
                      :props="{ label: 'name', value: 'code' }"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="报废数量"
                  show-overflow-tooltip
                  min-width="90"
                >
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.scrapGoodsQuantity"
                      placeholder="请输入"
                      size="mini"
                      onkeyup="value=value.replace(/[^\d]/g,'')"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="物料单位"
                  prop="goodsUnitName"
                  min-width="80"
                />
                <el-table-column
                  label="备注"
                  show-overflow-tooltip
                  min-width="150"
                >
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.scrapDetailRemark"
                      placeholder="请输入"
                      size="mini"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  fixed="right"
                  show-overflow-tooltip
                  min-width="80"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="删除"
                      placement="right-start"
                    >
                      <span
                        class="pointer tc"
                        @click="purchaseDelete(scope.$index, scope.row)"
                        ><i class="el-icon-delete"
                      /></span>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddDialog = false">取 消</el-button>
        <!-- 新增       -->
        <el-button
          v-if="ops === 'add'"
          v-loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="addSave"
          >保存</el-button
        >
        <!-- <el-button
          v-if="ops === 'add'"
          v-loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="addSave('confirm')"
          >保存并确认</el-button
        > -->
        <!--  修改      -->
        <el-button
          v-if="ops === 'modify'"
          v-loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="editSave"
          >保存</el-button
        >
        <!-- <el-button
          v-if="ops === 'modify'"
          v-loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="editSave('confirm')"
          >保存并确认</el-button
        > -->
      </div>
    </el-dialog>
    <!-- 查看报废单   -->
    <el-dialog
      title="查看物料报废"
      :visible.sync="isSeeDialog"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <div class="subTip">
          <span class="mr15"
            ><span class="mr5">报废单号：</span
            >{{ scrapForm.scrapBillNo || "系统自动生成" }}</span
          >
          <span class="mr15"
            ><span class="mr5">创建日期：</span
            >{{ scrapForm.createTime || dayjs().format("YYYY-MM-DD") }}</span
          >
          <span
            ><span class="mr5">创建人员：</span
            >{{ scrapForm.createPersonName }}</span
          >
        </div>
        <div class="addWuliaoBox">
          <el-form
            ref="scrapForm"
            disabled
            :model="scrapForm"
            :rules="rules"
            label-width="110px"
            label-position="left"
            class="dialogForm dialogInlineForm"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="报废类型">
                  <el-select
                        filterable
                    v-model="scrapForm.scrapBillType"
                    placeholder="报废类型"
                    size="mini"
                  >
                    <el-option
                      v-for="item in scrapBillTypeList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="报废人员">
                  <el-input
                    v-model="scrapForm.scrapPersonName"
                    placeholder="请输入内容"
                    size="mini"
                  >
                    <template slot="append">
                      <el-button
                        slot="append"
                        icon="el-icon-user"
                        @click="isperShow = true"
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item
              label="报废备注"
              class="inlineText"
              prop="scrapRemark"
            >
              <el-input
                v-model="scrapForm.scrapRemark"
                type="textarea"
                :rows="1"
                placeholder="请输入报废备注"
                size="mini"
                clearable
              />
            </el-form-item>
          </el-form>
          <div class="tableBox flex flex_column">
            <div class="tt flex flex_between">
              <span class="fw">报废明细</span>
            </div>
            <div ref="bigdialogTable" class="bigdialogTbCon">
              <el-table :data="scrapForm.detailList" border style="width: 100%">
                <el-table-column
                  label="物料编号"
                  prop="stockGoodsCode"
                  show-overflow-tooltip
                  min-width="110"
                />
                <el-table-column
                  label="物料类型"
                  prop="categoryName"
                  min-width="90"
                />
                <el-table-column
                  label="供应商"
                  prop="supplierName"
                  show-overflow-tooltip
                  min-width="90"
                />
                <el-table-column
                  label="物料名称"
                  prop="goodsName"
                  show-overflow-tooltip
                  min-width="110"
                />
                <el-table-column
                  label="规格型号"
                  prop="stockGoodsName"
                  min-width="90"
                />
                <el-table-column
                  label="库存数量"
                  prop="stockQuantity"
                  show-overflow-tooltip
                  min-width="120"
                />
                <el-table-column
                  label="出库库位"
                  show-overflow-tooltip
                  prop="stockArea"
                  min-width="150"
                >
                  <template slot-scope="{ row }">
                    <el-cascader
                      v-model="row.stockArea"
                      :show-all-levels="false"
                      size="mini"
                      disabled
                      :options="storageLocations"
                      :props="{ label: 'name', value: 'code' }"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="报废数量"
                  show-overflow-tooltip
                  min-width="90"
                  prop="scrapGoodsQuantity"
                />
                <el-table-column
                  label="物料单位"
                  prop="goodsUnitName"
                  min-width="80"
                />
                <el-table-column
                  label="备注"
                  show-overflow-tooltip
                  min-width="150"
                  prop="scrapDetailRemark"
                />
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isSeeDialog = false">取 消</el-button>
        <!-- 确定       -->
        <el-button
          v-if="ops === 'see'"
          type="primary"
          size="mini"
          @click="isSeeDialog = false"
          >确定</el-button
        >
        <!--  确认报废      -->
        <el-button
          v-if="ops === 'confirm'"
          v-loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="confirmSave"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--  选择物料  -->
    <selectMaterial
      :per-visible.sync="isMaterialShow"
      :selectList="scrapForm.detailList"
      @getMateriListData="selecdConfirm"
    />
    <!-- 人员寻找弹框   -->
    <per-redio-dialog
      :per-visible.sync="isperShow"
      @getEmployee="getEmployee"
    />
  </div>
</template>
<script>
import { arraySort } from "@/utils";
import naTable from "@/components/naTable";
import perRedioDialog from "@/components/perDialogRedio";
import selectMaterial from "@/components/selectMaterial";
import { mapGetters } from "vuex";
export default {
  name: "MaterielScrap",
  components: {
    naTable,
    perRedioDialog,
    selectMaterial,
  },
  computed: {
    ...mapGetters(["name", "userInfo"]),
  },
  data() {
    return {
      isperShow: false,
      isMaterialShow: false, // 物料弹框是否打开
      isSeeDialog: false, // 查看弹框是否打开
      radioSelect: null,
      isAllMateriel: true, // 默认显示全部报废物料
      isMaterielDialog: false, // 选择物料弹框是否打开
      addLoading: false, // 保存加载效果
      ops: "add", // 操作，新建，编辑，查看，确认
      isAddDialog: false, // 新建报废单弹框打开事件
      searchLoading: false,
      classIndex: null, // 物料分组选中索引
      scrapBillTypeList: [], // 报废类型列表
      allSupliers: [],
      scrapForm: {
        scrapBillType: "",
        scrapPeopleCode: "", // 报废人员code
        scrapPersonName: "", // 报废人员Name
        scrapRemark: "",
        createor: "", // 创建人员
        detailList: [],
      },
      scrapBillID: null, // 报废单ID
      // 报废单列表搜索条件
      search: {
        QueryDataBaseFiled: "",
        pageIndex: 1,
        pageSize: 30,
        likeWords: "",
        scrapBillType: "",
        warehouseCode: "",
        scrapBillState: -1,
      },
      total: 0,
      marLoading: false, // 报废物料列表加载效果
      // 报废单选择物料筛选条件
      checkMaterielSearch: {
        pageIndex: 1,
        pageSize: 30,
        warehouseCode: "",
        groupCdoe: "",
      },
      storageLocations: [], // 库位列表
      marTotal: 0,
      materielLits: [], // 报废物料列表
      materielGroup: [], // 物料分组
      currentRow: {}, // 报废物料选中当前项
      dataLits: [], // 报废单列表
      tableHead: [], // 表头列表
      tableHeight: null,
      warhouseList: [], // 所有仓库列表
      // 表格操作按钮
      operations: [
        [
          {
            text: "查看",
            key: "see",
          },
          {
            text: "修改",
            key: "modify",
          },
        ],
        [
          {
            text: "确认报废",
            key: "confirm",
          },
        ],
        [
          {
            text: "删除",
            key: "delete",
          },
        ],
      ],
      rules: {
        warehouseCode: [
          {
            required: true,
            message: "请选择报废仓库",
            trigger: "change",
          },
        ],
        scrapRemark: [
          {
            required: true,
            message: "请填写报废备注",
            trigger: "change",
          },
        ],
      },

      tableData: {
        headId: "head", //表头列显隐组件所需ID-避免多个页面id重复问题
        tableId: "scrapBillID", //表格列表key,也就是一条数据的唯一标识
        senior: false, //高级搜索是否显示
        disableWord: "", //是否禁用显示的字段
        disableStatus: "", //判断未禁用的状态值
        // addTitle: '', //新建按钮名称-为''则不显示，为undefine则为新建
        addPermission: "MenuCode5-7-1-1", //新建按钮权限
        addIcon: "", //新建按钮icon
        voidWord: "", //需要查询作废的字段
        statusList: [], //状态筛选条件列表
        statusWord: "", //状态筛选的字段
        refresh: true, //刷新按钮
        showSum: true, //显示合计
        //表格按钮
        operationBtn: [
          {
            title: "查看", //按钮名称
            methodsName: "seeScrap", //按钮绑定方法的字段
          },
          {
            title: "修改", //按钮名称
            methodsName: "updateClick", //按钮绑定方法的字段
            permission: "MenuCode5-7-1-2", //按钮权限
            hideCondition: {
              //按钮显隐条件
              prop: "scrapBillState", //控制显隐的状态字段
              show: [
                //有哪些状态可以使用-值必须跟状态的类型保持一致
                0,
              ],
            },
          },
          {
            title: "确认", //按钮名称
            methodsName: "confirmClick", //按钮绑定方法的字段
            permission: "MenuCode5-7-1-3", //按钮权限
            hideCondition: {
              //按钮显隐条件
              prop: "scrapBillState", //控制显隐的状态字段
              show: [
                //有哪些状态可以使用-值必须跟状态的类型保持一致
                0,
              ],
            },
          },
          {
            title: "删除", //按钮名称
            methodsName: "deleteScrap", //按钮绑定方法的字段
            permission: "MenuCode5-7-1-4", //按钮权限
            hideCondition: {
              //按钮显隐条件
              prop: "scrapBillState", //控制显隐的状态字段
              show: [
                //有哪些状态可以使用-值必须跟状态的类型保持一致
                0,
              ],
            },
          },
          {
            title: "复制", //按钮名称
            methodsName: "copyScrap", //按钮绑定方法的字段
            permission: "MenuCode5-7-1-5", //按钮权限
            hideCondition: {
              //按钮显隐条件
              prop: "scrapBillState", //控制显隐的状态字段
              show: [
                //有哪些状态可以使用-值必须跟状态的类型保持一致
                -1,
              ],
            },
          },
        ],
        //表格内容
        tbody: [],
        //表格表头
        thead: [],
      },
    };
  },
  created() {
    // 获取物料报废列表表格表头
    this.getTableHead();
    // 所有报废的列表
    this.getDataLists();
    // 得到所有仓库列表
    this.getWarehouseList();
    // 报废类型列表
    this.getScrapTypeList();
    // 库区库位
    this.getStorageLocations();

    this.getSupplier();
  },
  mounted() {},
  methods: {
    // 复制
    copyScrap(data) {
      this.ops = "add";
      // 获取报废单详情
      this.getScrapInfo(data.scrapBillID);
      this.isAddDialog = true;
    },

    // 供应商选择改变事件
    supplierChange(row, val) {
      row.goodsCode = "";
      row.specificationCode = "";
      row.materialList = [];
      row.goodsSpecificationList = [];
      row.goodsType = "";
      this.$api.mater
        .GetGoodsSpecificationBySupplierCode({
          queryBy: 0,
          queryValue: val,
        })
        .then((res) => {
          row.materialList = res;
        });
      this.$forceUpdate();
    },

    //物料下拉选择事件
    handleMaterialNameChange(row, index, e) {
      if (index == this.scrapForm.detailList.length - 1) {
        this.scrapForm.detailList.push({
          stockGoodsCode: "",
          scrapGoodsQuantity: 0,
          scrapDetailRemark: "",
          warehouseAreaCode: "",
          areaShelfCode: "",
          materialList:[],
          goodsSpecificationList:[],
          rowKey: Date.now(),
        });
      }
      row.stockGoodsCode = e;
      row.specificationCode = "";
      row.materialList.forEach((item, i) => {
        if (item.goodsCode == e) {
          row.categoryName = item.goodsType;
          this.$set(row,'goodsSpecificationList',item.goodsSpecificationList)
          row.goodsUnitName = item.goodsUnit;
        }
      });
      this.$forceUpdate()
    },

    //规格下拉选择事件
    handleSpecificationChange(row,index,e){
      row.goodsSpecificationList.forEach((item, i) => {
        if (item.specificationCode == e) {
          this.$set(row,'specificationCode',item.specificationCode)
          this.$set(row,'stockQuantity',item.stockQuantity)
          this.$set(row,'productionBatchList',item.productionBatchList)
        }
      });
    },

    //生产批次选择事件
    handleBatchChange(row, value) {
      // console.log(value)
      // return
      this.$set(row, "storageLocations", value.warehouseAreaTreeList);
      this.$set(row, "stockArea", []);
      this.$set(row, "stockQuantity", "");
      this.$set(row.stockArea, 0, value.warehouseAreaTreeList[0].code);
      this.$set(
        row.stockArea,
        1,
        value.warehouseAreaTreeList[0].areaShelfTreeList[0].code
      );
      this.$set(
        row,
        "stockQuantity",
        value.warehouseAreaTreeList[0].areaShelfTreeList[0].stockQuantity
      );
      this.$set(row, "productionBatchNumber", value.productionBatchNumber);
      this.$set(row, "productionBatchCode", value.productionBatchCode);
      this.$set(row, "productionDate", value.productionDate);
      this.$forceUpdate();
    },

    // 报废人员选择确定
    getEmployee(val) {
      this.scrapForm.scrapPeopleCode = val.employeeCode;
      this.scrapForm.scrapPersonName = val.employeeName;
    },
    // 报废类型列表
    getScrapTypeList() {
      this.$api.warehouse.GetAllScrapBillType().then((res) => {
        this.scrapBillTypeList = res;
        this.scrapForm.scrapBillType = res[0].code;
      });
    },

    // 获取供应商
    getSupplier() {
      this.$api.mater.GetAllSuppliers().then((res) => {
        this.allSupliers = res;
      });
    },
    // 新建保存
    addSave(type) {
      const parmas = this.scrapForm;
      console.log(parmas);
      this.$refs.scrapForm.validate((valid) => {
        if (valid) {
          if (this.scrapForm.detailList.length < 2) {
            this.$message({
              message: "请选择报废物料",
              type: "warning",
            });
            return false;
          }
          let arr = JSON.parse(JSON.stringify(this.scrapForm.detailList))
          let isvalid = true;
          arr.pop()
          arr.forEach((item) => {
            if (item.stockArea) {
              item.warehouseAreaCode =
                (item.stockArea && item.stockArea[0]) || item.warehouseAreaCode;
              item.areaShelfCode =
                (item.stockArea && item.stockArea[1]) || item.areaShelfCode;
              if (item.stockArea.length < 1) {
                isvalid = false;
                return;
              }
            } else {
              isvalid = false;
            }
          });
          if (!isvalid) {
            this.$message({
              message: "请选择库位",
              type: "warning",
            });
            return false;
          }
          this.scrapForm.detailList = JSON.parse(JSON.stringify(arr))
          this.addLoading = true;
          if (type === "confirm") {
            this.$api.warehouse
              .AddGoodsScrapBill(parmas)
              .then((res) => {
                const parmas = {
                  entityID: res.scrapBillID,
                };
                this.addPurLoading = true;
                this.$api.warehouse
                  .SureGoodsScrapBill(parmas)
                  .then(() => {
                    this.isAddDialog = false;
                    this.addLoading = false;
                    this.getDataLists();
                    this.$message({
                      message: "确认成功",
                      type: "success",
                    });
                  })
                  .catch(() => {
                    this.addLoading = false;
                  });
                // this.$message({
                //   message: "保存成功",
                //   type: "success",
                // });
                // this.isAddDialog = false;
                // this.addLoading = false;
                // this.getDataLists();
              })
              .catch(() => {
                this.addLoading = false;
              });
          } else {
            this.$api.warehouse
              .AddGoodsScrapBill(parmas)
              .then(() => {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                this.isAddDialog = false;
                this.addLoading = false;
                this.getDataLists();
              })
              .catch(() => {
                this.addLoading = false;
              });
          }
        }
      });
    },
    // 编辑保存
    editSave(type) {
      const parmas = this.scrapForm;
      this.$refs.scrapForm.validate((valid) => {
        if (valid) {
          if (this.scrapForm.detailList.length <= 0) {
            this.$message({
              message: "请选择报废物料",
              type: "warning",
            });
            return false;
          }
          this.addLoading = true;
          this.scrapForm.detailList.forEach((item) => {
            item.warehouseAreaCode =
              (item.stockArea && item.stockArea[0]) || item.warehouseAreaCode;
            item.areaShelfCode =
              (item.stockArea && item.stockArea[1]) || item.areaShelfCode;
            if (item.stockArea.length < 1) {
              isvalid = false;
              return;
            }
          });
          if (type === "confirm") {
            this.$api.warehouse
              .UpdateGoodsScrapBill(parmas)
              .then(() => {
                const obj = {
                  entityID: this.scrapForm.scrapBillID,
                };
                this.addPurLoading = true;
                this.$api.warehouse
                  .SureGoodsScrapBill(obj)
                  .then(() => {
                    this.isAddDialog = false;
                    this.addLoading = false;
                    this.getDataLists();
                    this.$message({
                      message: "确认成功",
                      type: "success",
                    });
                  })
                  .catch(() => {
                    this.addLoading = false;
                  });
              })
              .catch(() => {
                this.addLoading = false;
              });
          } else {
            this.$api.warehouse
              .UpdateGoodsScrapBill(parmas)
              .then(() => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.isAddDialog = false;
                this.addLoading = false;
                this.getDataLists();
              })
              .catch(() => {
                this.addLoading = false;
              });
          }
        }
      });
    },
    // 确认报废单
    confirmSave() {
      const parmas = {
        entityID: this.scrapBillID,
      };
      this.$confirm("确定报废?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.addPurLoading = true;
        this.$api.warehouse
          .SureGoodsScrapBill(parmas)
          .then(() => {
            this.isSeeDialog = false;
            this.addLoading = false;
            this.getDataLists();
            this.$message({
              message: "确认成功",
              type: "success",
            });
          })
          .catch(() => {
            this.addLoading = false;
          });
      });
    },
    // 库区库位
    getStorageLocations() {
      const parmas = {
        warehouseCode: "",
      };
      this.$api.warehouse.GetStockQueryAreaTreeView(parmas).then((res) => {
        this.storageLocations = res;
      });
    },
    // 删除报废明细项
    purchaseDelete(index, data) {
      if (data.scrapBillID) {
        const parmas = {
          entityID: data.scrapBillID,
        };
        this.$api.warehouse.DeleteScrapBillDetail(parmas).then((res) => {
          if (res.isDelete) {
            this.scrapForm.detailList.splice(index, 1);
          } else {
            this.$message({
              message: "该报废单明细不能删除",
              type: "warning",
            });
          }
        });
      } else {
        this.scrapForm.detailList.splice(index, 1);
      }
    },
    // 物料选择确认
    selecdConfirm(data) {
      const arr = JSON.parse(JSON.stringify(data));
      arr.forEach((item) => {
        // item.scrapDetailRemark = ''
        // item.scrapGoodsQuantity = 1
        item.stockQuantity = item.stockSumQuantity;
        item.unitCode = item.goodsUnitCode;
        item.unitName = item.goodsUnitName;
      });
      this.scrapForm.detailList = arr;
    },
    // 新建点击事件
    newAddClick() {
      this.isAddDialog = true;
      this.ops = "add";
      this.scrapForm.scrapPeopleCode = this.userInfo.employeeCode;
      this.scrapForm.scrapPersonName = this.userInfo.employeeName;
      this.scrapForm.detailList.push({
          stockGoodsCode: "",
          scrapGoodsQuantity: 0,
          scrapDetailRemark: "",
          warehouseAreaCode: "",
          areaShelfCode: "",
          materialList:[],
          goodsSpecificationList:[],
          rowKey: Date.now(),
        });
    },
    // 新增物料点击事件
    selecdWl() {
      this.isMaterialShow = true;
    },
    // 查看报废单
    seeScrap(data) {
      this.ops = "see";
      this.isSeeDialog = true;
      // 获取报废单详情
      this.getScrapInfo(data.scrapBillID);
    },
    // 修改点击事件
    updateClick(data) {
      this.ops = "modify";
      // 获取报废单详情
      this.getScrapInfo(data.scrapBillID);
      this.isAddDialog = true;
    },
    // 确认报废单点击事件
    confirmClick(data) {
      this.ops = "confirm";
      this.isSeeDialog = true;
      // 获取报废单详情
      this.getScrapInfo(data.scrapBillID);
      this.scrapBillID = data.scrapBillID;
    },
    // 删除报废单
    deleteScrap(row) {
      const parmas = {
        entityID: row.scrapBillID,
      };
      this.$confirm("确定删除该报废单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.warehouse.DeleteGoodsScrapBill(parmas).then(() => {
          this.getDataLists();
          this.$message({
            message: "删除成功",
            type: "success",
          });
        });
      });
    },
    // 获取报废单详情
    getScrapInfo(id) {
      const parmas = {
        queryBy: 1,
        queryValue: id,
      };
      this.$api.warehouse.GetSingleGoodsScrapBill(parmas).then((res) => {
        this.scrapForm = res;
        const arr = [...res.detailList];
        arr.forEach((item) => {
          const newArr = [];
          newArr.push(item.warehouseAreaCode, item.areaShelfCode);
          item.stockArea = newArr;
        });
        this.scrapForm.detailList = arr;
        console.log(this.scrapForm);
      });
    },
    // 单选事件
    handleRadioChange(e, row) {
      e.stopPropagation();
      this.currentRow = Object.assign({}, row);
    },
    // 给选中一行添加class
    tableRowClassName({ row }) {
      if (this.currentRow.id === row.id) {
        return "selectd";
      }
    },
    // 得到所有仓库列表
    getWarehouseList() {
      this.$api.warehouse.getWarehouseList().then((res) => {
        this.warhouseList = res;
        this.checkMaterielSearch.warehouseCode = res[0].warehouseCode;
        this.scrapForm.warehouseCode = res[0].warehouseCode;
      });
    },
    // 合计方法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "scrapSumValue") {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = sums[index]++;
          } else {
            sums[index] = " ";
          }
        }
      });

      return sums;
    },
    // 所有报废的列表
    getDataLists() {
      const parmas = this.search;
      this.searchLoading = true;
      this.$api.warehouse
        .GetMatchPageGoodsScrapBills(parmas)
        .then((res) => {
          this.searchLoading = false;
          this.tableData.tbody = res.list;
          this.search.total = res.totalCount;
        })
        .catch(() => {
          this.searchLoading = false;
        });
    },
    // 获取仓库管理列表表格表头
    getTableHead() {
      const parmas = {
        tableCode: this.$config.goodsScrapBillList,
      };
      this.$api.common.getAllTableHead(parmas).then((res) => {
        res.sort(arraySort("columnSort"));
        this.tableData.thead = res;
      });
    },
    // 关闭弹框事件
    closeDialog() {
      // 关闭弹框的时候清空数据
      if (this.$refs.scrapForm) {
        this.$refs.scrapForm.resetFields();
      }
      this.scrapForm = this.$options.data().scrapForm;
    },
  },
};
</script>
<style lang="scss" scoped>
.spot {
  width: 6px;
  height: 6px;
  display: inline-block;
  border-radius: 100%;
}

.bigdialogTbCon {
  width: 100%;
}

.addWuliaoBox {
  padding: 10px 16px;

  .tableBox {
    margin-top: 16px;
    border: 1px solid #e6e6e6;
    border-bottom: none;
    border-radius: 8px 8px 0 0;
    overflow: hidden;

    .tt {
      width: 100%;
      height: 38px;
      line-height: 38px;
      padding-left: 16px;
      background: #f7f8fa;
      border-radius: 8px 8px 0 0;
    }
  }
}

.subTip {
  border-bottom: 1px #e6e6e6 solid;
  background: #f5f6f9;
  padding: 8px 16px;
}

.allMateriel {
  line-height: 44px;
  padding-left: 16px;

  &:hover {
    background: #3f61f110;
    color: #3f61f1;
  }
}

.allMateriel.crt {
  background: #3f61f110;
  color: #3f61f1;
}

.reservoirBox {
  height: 100%;

  .rgRewBox {
    width: calc(100% - 260px);
    height: 100%;
    position: relative;

    .btnCon {
      border-bottom: none;
    }
  }

  .lfReservoir {
    width: 260px;
    border-right: 1px #eee solid;
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.04);

    .materielList {
      li {
        padding: 8px 16px;
        cursor: pointer;

        &:hover,
        &.crt {
          background: #3f61f110;
          color: #3f61f1;
        }
      }
    }
  }

  .navTT {
    line-height: 22px;
    padding: 16px;
  }
}
</style>
<style lang="scss">
.selectd {
  td {
    background: #3f61f110;
  }
}
</style>
